package top.lingkang.hibernate5.dao.impl;

import org.hibernate.SessionFactory;
import top.lingkang.hibernate5.dao.Query;
import top.lingkang.hibernate5.dao.QueryHandler;
import top.lingkang.hibernate5.dao.TupleResult;

import javax.persistence.Tuple;
import java.lang.reflect.Method;

/**
 * @author lingkang
 * created by 2023/10/8
 */
public class ListQueryHandler implements QueryHandler {
    private SessionFactory sessionFactory;
    private Class<?> returnType;
    private Query query;
    private boolean isNative;

    public ListQueryHandler(SessionFactory sessionFactory, Class<?> returnType, Query query, boolean isNative) {
        this.sessionFactory = sessionFactory;
        this.returnType = returnType;
        this.query = query;
        this.isNative = isNative;
    }

    @SuppressWarnings("deprecation")
    @Override
    public Object doQuery(Method method, Object[] args) throws Throwable {
        return getQuery(query, args, Tuple.class).setResultTransformer(new TupleResult(returnType)).list();
    }

    private org.hibernate.query.Query getQuery(Query query, Object[] args, Class<?> returnType) {
        org.hibernate.query.Query exeQuery = sessionFactory.openSession().createQuery(query.value(), returnType);
        if (args != null)
            for (int i = 0; i < args.length; i++)
                exeQuery.setParameter(i + 1, args[i]);
        return exeQuery;
    }
}
